<pre>
# pdf_cherry.py
# Author: Vasudev Ram - http://www.dancingbison.com
# Program to generate PDF using CherryPy and xtopdf.
# Requires Reportlab v1.21 open source version.
# Written using CherryPy 3.2.4 and Python 2.7.5.

import os
from PDFWriter import PDFWriter
from file_utils import change_file_ext
from textwrap import TextWrapper

import os
import cherrypy
from cherrypy.lib.static import serve_file

class Root(object):
    pass

class Upload(object):

    def index(self):
        return """
        &lt;html&gt;&lt;head&gt;&lt;title&gt;PDF in a CherryPy&lt;/title&gt;&lt;/head&gt;&lt;body&gt;
            &lt;h3&gt;PDF in a CherryPy&lt;/h3&gt;
            &lt;h4&gt;Upload a text file to convert to PDF.&lt;/h4&gt;
            &lt;form action="text_to_pdf" method="post" enctype="multipart/form-data"&gt;
            filename: &lt;input type="file" name="uploadFile" /&gt;&lt;br/&gt;
            &lt;input type="submit"/&gt;
            &lt;/form&gt;
        &lt;/body&gt;&lt;/html&gt;
        """
    index.exposed = True

    def text_to_pdf(self, uploadFile):
        txt_filename = uploadFile.filename
        pdf_filename = change_file_ext(txt_filename, ".txt", ".pdf")
        pw = PDFWriter(pdf_filename)
        pw.setFont("Courier", 10)
        pw.setHeader("Text file: " + txt_filename + \
            " PDF file: " + pdf_filename)
        pw.setFooter("Generated by CherryPy, xtopdf and Reportlab")
        wrapper = TextWrapper(width = 120, drop_whitespace = True,
            break_long_words = True)
        for lin in uploadFile.file.readlines():
            lines = wrapper.wrap(lin)
            for lin2 in lines:
                pw.writeLine(lin)
        pw.close()
        respons = "&lt;html&gt;&lt;head&gt;&lt;title&gt;PDF in a CherryPy&lt;/title&gt;&lt;/head&gt;"
        respons += "&lt;body&gt;&lt;h3&gt;PDF in a CherryPy&lt;/h3&gt;"
        respons += "Text file: " + txt_filename + "&lt;br/&gt;"
        respons += 'PDF file: &lt;a href="/download/?filepath=' + os.getcwd() + \
            "\\" + pdf_filename + '"&gt;' + \
            pdf_filename + '&lt;/a&gt;&lt;br/&gt;'
        respons += "&lt;/body&gt;&lt;/html&gt;"
        return respons

    text_to_pdf.exposed = True

class Download:

    def index(self, filepath):
        return serve_file(filepath, "application/x-download", "attachment")
    index.exposed = True

def main():
    root = Root()
    root.upload = Upload()
    root.download = Download()
    cherrypy.quickstart(root)

if __name__ == '__main__':
    main()

# EOF
</pre>
